package com.sotb.sender;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;

import com.android.internal.telephony.ITelephony;

public class MyPhoneBroadcastReceiver extends BroadcastReceiver {

	private final static String TAG = SMSSenderService.TAG;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.i(TAG, "[Broadcast]"+action);
		
		//呼入电话
		if(action.equals(SMSSenderService.B_PHONE_STATE)){
			Log.i(TAG, "[Broadcast]PHONE_STATE");
			doReceivePhone(context,intent);
		}
	}
	
	/**
	 * 处理电话广播.
	 * @param context
	 * @param intent
	 */
	public void doReceivePhone(Context context, Intent intent) {
		String phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
		TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
		int state = telephony.getCallState();
		
		switch(state){
		case TelephonyManager.CALL_STATE_RINGING:
			Log.i(TAG, "[Broadcast]等待接电话="+phoneNumber);
			try {
				ITelephony iTelephony = PhoneUtils.getITelephony(telephony);
				iTelephony.answerRingingCall();//自动接通电话
				//iTelephony.endCall();//自动挂断电话
			} catch (Exception e) {
				Log.e(TAG, "[Broadcast]Exception="+e.getMessage(), e);
				Intent intent1 = new Intent("android.intent.action.MEDIA_BUTTON");  
			    KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK);  
			    intent1.putExtra("android.intent.extra.KEY_EVENT",keyEvent);  
			    context.sendOrderedBroadcast(intent1,"android.permission.CALL_PRIVILEGED");  
			    intent1 = new Intent("android.intent.action.MEDIA_BUTTON");  
			    keyEvent = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK);  
			    intent1.putExtra("android.intent.extra.KEY_EVENT",keyEvent);  
			    context.sendOrderedBroadcast(intent1,"android.permission.CALL_PRIVILEGED");
			}
			break;
		case TelephonyManager.CALL_STATE_IDLE:
			Log.i(TAG, "[Broadcast]电话挂断="+phoneNumber);
			break;
		case TelephonyManager.CALL_STATE_OFFHOOK:
			Log.i(TAG, "[Broadcast]通话中="+phoneNumber);
			break;
		}
	}

}
